//
//  MsgUtils.swift
//  Runner
//
//  Created by zzzzzzz on 2020/10/26.
//

import Foundation

public class MsgUtils {
 
    /**
       * 日志保存目录
       */
    private static var LOG_PATH:String!;

      /**
       * 日志保存的目录
       * 如果没有获取存储权限,mars会自动存到getLogCachePath()目录
       *
       * @param context
       * @return
       */
    public static func getLogPath() -> String {
          if (LOG_PATH.isEmpty) {
            //存在什么地方适合

            let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

            let documentDirectory = paths[0]

            let fileName = "test.log";

            let documentDirectoryUrl = URL.init(string: documentDirectory)
            
            LOG_PATH = documentDirectoryUrl?.appendingPathComponent(fileName).absoluteString
             
            // LOG_PATH = path + File.separator + "kanjian_app/xlog";
          }

          return LOG_PATH;
      }

      public func isMainThread()->Bool {
        
        return Thread.isMainThread;
      }
    
   private static func parseObject<T:Codable>(withJSONObject obj:Any?,modelType:T.Type)->T?{
        /*
         jsonObject->data->model
         */
        
        guard let obj = obj else {
            return nil
        }
        do{
            
            let json = obj as! String
            let jsonData:Data = json.data(using: .utf8)!

            //let jsonData = try JSONSerialization.data(withJSONObject: obj as Any, options:[])

            let model = try JSONDecoder().decode(modelType, from: jsonData)
            return model
        }catch{
            print(error)
            return nil
        }
    }

      /**
       * 解析待发送的消息
       *
       * @param json
       * @return
       */
    public static func parseToMsgSendBean( json:String)->SendMsgBean {
        return parseObject(withJSONObject: json, modelType: SendMsgBean.self)!;
      }

      /**
       * 解析服务端响应对象
       *
       * @param json
       * @return
       */
    public static func  parseToMsgRespBean( json:String)->RespBean {
        return parseObject(withJSONObject: json, modelType: RespBean.self)!;
      }

    
    
    
    
      /**
       * 获取服务器响应消息uuid
       *
       * @param json
       * @return
       */
    public static func getRespMsgUUid( json:String) ->String{
          let respBean = parseToMsgRespBean(json: json);
          return respBean.getMsgId() 
      }

    
    
       /**
        * 是否是服务器响应的消息
        *
        * @param data 消息内容
        * @return
        */
    
    public static func isServerRespMsg(data:Data) ->Bool{
        let respBean = ProtocolUtil.getReceiveMsgType(buffer:[UInt8](data));
        return (respBean != 0);
      }
    
      /**
       * 获取UUID UUID（去掉中横线）
       *
       * @return
       */
      public static func  getUUID()->String {
        return UUID().uuidString.replacingOccurrences(of: "-", with: "")
      }

      /**
       * 解析json获取roomID
       *
       * @param json
       * @return
       */
    public static func  parseToRoomId( json:String)->String {
          do {
            
            let jsonData:Data = json.data(using: .utf8)!
            let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? NSDictionary

              //这里解析 旧的方法 新的改了数据结构
//              let number = jsonObject?["roomId"] as! String;
//              return number;
              
                let dic111 = NSObjetJohn.dictionary(withJsonString: json);
                if(dic111.keys.contains("message")){
                    if(dic111["message"] as! String == "解密失败"){
                        print("解密失败");
                        return "";
                    }
                }
              
              let resultJson = jsonObject?["content"] as! String;
              let dic =  NSObjetJohn.dictionary(withJsonString: resultJson);
              let number = dic["roomId"] as? String ?? "0";
              return number
          } catch (let error) {
            print(error.localizedDescription)
          }
          return "";
      }

    public static func toBoolValue(number:Bool?)->Bool {
        return number ?? false;
      }

    public static func numberToIntValue( number:NSNumber?)->Int {
        return number?.intValue ?? 0 ;
      }

    public static func numberToLongValue( number:NSNumber?)->CLong{
        return  number?.intValue ?? 0;
      }

      public static func numberToFloatValue( number:NSNumber?) ->Float {
        return number?.floatValue ?? 0.0;
      }

    
}
